package com.wuzhen.wzzt.core.utils;

import com.google.gson.Gson;
import com.wuzhen.wzzt.model.LocationCommonDto;
import com.wuzhen.wzzt.model.LocationDto;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class AddressUtils {
    public static void main(String[] args) {
        getLngAndLat("合肥市包河区金寨路96号");
    }

    public static LocationDto getLngAndLat(String address) {
        String url = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=o4ktk6yLPwmS7Gc4MF3RrO8t8hCGmcEB";   //这里需要自己申请百度ak
        try {
            String json = loadJSON(url);
            Gson gson = new Gson();
            LocationCommonDto locationCommonDto = gson.fromJson(json, LocationCommonDto.class);
            if (locationCommonDto.getStatus() == 0) {
                return locationCommonDto.getResult().getLocation();
            }
        }catch (Exception e){
            log.error("地址转换成经纬度失败 address= {}",address);
        }
        return null;
    }



    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }
}
